import Request from 'luch-request'
import { useSystemStore } from '@/store/system.js'

const BASE_URL = 'https://api.uomg.com/api'
// const HEADER = {
//   'Content-Type': 'application/json;charset=UTF-8;',
//   Accept: 'application/json, text/plain, */*'
// }

function createRequest () {
  return new Request({
    baseURL: BASE_URL,
    // header: HEADER,
    custom: {
      auth: true
    }
  })
}

const request = createRequest()
/**
 * 请求拦截器
 */
request.interceptors.request.use(
  (options) => {
    if (options.custom?.auth) {
      const systemStore = useSystemStore()
      if (!systemStore.isLogin) {
        console.log('请先登录')
        // token不存在跳转到登录页
        return Promise.reject(options)
      }
      // options.header = assign(options.header, {
      //   authorization: `Bearer ${systemStore.getToken}`
      // })
    }
    return options
  },
  (options) => Promise.reject(options)
)

/**
 * 响应拦截器
 */
request.interceptors.response.use(
  async (response) => {
    const { data, statusCode } = response
    if (statusCode === 200) {
      return data
    }
    return Promise.reject(response)
  },
  (response) =>
  // 请求错误做点什么
    Promise.reject(response)
)

const get = (url, params) => {
  return request.get(url, {
    params
  })
}
const post = (url, params, config) => {
  return request.post(url, params, config)
}

export { request, get, post }
